# --**coding:utf-8**--
# Create by author: hemq

from django.shortcuts import render, render_to_response
from channel.models import Androidnodestatus, HistoryChannelapk, ChannelListConfig, \
    Channellist, HisChannelDownload, PreChannelDownload, ChannelConfigList
import os, getModelInfo, threading, datetime
from channel.settings import dev, filetool, channelconfig, channelBuildApk
from django.http import JsonResponse, HttpResponse
from channel.python import Util, android, Const
import channel.settings.apkManage as manage
from django.views.decorators.csrf import csrf_exempt
from datetime import datetime
from config import configScr, configInfo


# Create your views here.

def get_channel_apk(request):
    # 签名文件等数据存储于nodeconfig表

    # 获取 数据库存储的信息作为参数

    # 调用android.py，进行渠道包构建，注意：签名文件，android buildtool工具路径，构建完的包存储

    return True


def index(request):
    # return render(request, 'channnewnew/login.html')

    return render(request, 'channnewnew/index.html')


def retUploadApk(request):
    '''
    return：上传母包页面
    '''
    return render(request, 'channnewnew/uploadApk.html')


def get_base_apk(request):
    '''
    接收上传母包
    '''
    if request.method == 'POST':
        # 获取版本号
        apkVersion = request.POST['version']
        print 'apkversion', apkVersion
        filetool.handle_upload_file(request.FILES['file'], str(request.FILES['file']))
        apkName = str(request.FILES['file'])
        if apkName.split('.')[1] != 'apk':
            return {"code": 201, "msg": "上传文件错误"}
        # 获取渠道号
        channelName = channelconfig.channelName
        preVersion = configScr.getVersionFromFile()
        # print 'preversion',preVersion
        if apkVersion != preVersion:
            # clean pre channel apk dir
            configScr.channelApkDelete()
            print '删除成功'
            # 存储版本号
            with open('versionFile.txt', 'wr+') as file:
                file.writelines(apkVersion)
                file.close
            print '新版本号存储成功'
            # 母包传输成功后，跳转至选择渠道号页面，页面增加提醒，母包传输成功提醒
            return render(request, 'channnewnew/testLoad.html')
        else:
            print '版本号一致'
            return render(request, 'channnewnew/testLoad.html')
    else:
        return HttpResponse('upload fail')


def build_channel_apk(request):
    # 每次构建前，删除channelApk文件夹，保证每次该文件夹仅存储最新渠道包
    filetool.delChannelApkDir()
    # creat new channelApk dir
    filetool.creatChannelApk()
    # 根据母包生成对应的渠道包
    channelNum = getModelInfo.get_360_info_channelNum()
    chanelName = getModelInfo.get_360_info_channelName()
    chanApkName = ''
    version = ''
    loginfo1 = ''
    loginfo2 = ''
    loginfo3 = ''
    loginfo4 = ''
    loginfo5 = ''
    loginfo6 = ''
    for channelIndex in range(len(channelNum)):
        eachChannelName = chanelName[channelIndex]
        eachChannelNum = channelNum[channelIndex]
        # copy母包--->得出渠道包
        # chanApkName = './channelApk/'+eachChannelName+'-'+eachChannelNum+'.apk'
        apkName = eachChannelName + '-' + eachChannelNum + '.apk'
        chanApkName = 'channel/staticc/channelApk/' + apkName

        # 拼接apk下载路由，存储于数据库
        apkDownloadUrl = channelconfig.channelApkppath + apkName
        loginfo1 = '渠道包存储新建完毕···'
        # 若有必要，生成对应二维码,将二维码链接/icon存储于db
        # channelBuildApk.createQRCode(apkDownloadUrl,eachChannelName,channelNum)
        # 获取版本号
        version = filetool.getVersionFromFile()
        loginfo2 = '版本号获取完毕···'
        # case 1: 添加url至db
        downloadInfo = Androidnodestatus(status=version, title=eachChannelName, actionurl=apkDownloadUrl)
        downloadInfo.save()
        loginfo3 = 'url信息添加完毕···'
        # insert channelapk --> table ：history channelApk
        channelapkDownUrl = channelconfig.historyChannelApkPath + version + '/' + apkName
        historychannelApk = HistoryChannelapk(version=version, channelnum=eachChannelName, downloadrl=channelapkDownUrl)
        historychannelApk.save()
        loginfo4 = '渠道包归档信息url添加完毕'
        # copy 母包
        baseApkName = filetool.getBaseApkPath()
        Util.copyFile(baseApkName[0], chanApkName)
        loginfo5 = 'copy 成功···'
        # 向渠道包中添加对应的渠道文件信息
        channelBuildApk.getAChannelApk(chanApkName, eachChannelNum)
        loginfo6 = '渠道信息添加成功···'
        print eachChannelName + u'渠道包构建完毕'
        # 渠道包签名 有需要可调用
        # channelBuildApk.SignApk()
    # 渠道包文件路径
    channleApkPath = './channel/staticc/channelApk/'
    # 母包归档处理 (已验证)
    manage.apkManage(channleApkPath).baseApkManage()
    loginfo7 = 'base apk 归档成功···'
    # 渠道包归档 （已验证）
    manage.apkManage(channleApkPath).channelApkMange()
    loginfo8 = 'channel apk 归档成功···'
    return render(request, 'channnewnew/buildResult.html',
                  {'loginfo1': loginfo1, 'loginfo2': loginfo2, 'loginfo3': loginfo3,
                   'loginfo4': loginfo4, 'loginfo5': loginfo5, 'loginfo6': loginfo6, 'loginfo7': loginfo7,
                   'loginfo18': loginfo8})


class myThread_build_360(threading.Thread):
    def __init__(self, canshu):
        threading.Thread.__init__(self)
        self.camshu = canshu
        pass

    def run(self):
        startTime = datetime.datetime.now()
        print 'startTime:', startTime
        print '开始360'
        # get 360 base apk
        baseapk = configScr.getBaseApkPath()  # baseapk type:array
        # get channelCode && channelName
        code = getModelInfo.new_360_code()
        name = getModelInfo.new_360_name()
        version_info = filetool.getVersionFromFile()
        for indexInfo in range(len(code)):
            # get each name && code
            eachCode = code[indexInfo]
            eachName = name[indexInfo]
            eachChannelApk = '360-' + eachName + '-' + eachCode + '.apk'
            configScr.dirExit(configInfo.presentChannelApkPath)
            preChannelApkDir = configInfo.presentChannelApkPath + eachChannelApk
            signApkDir = configInfo.signapkName + version_info + '_' + eachChannelApk
            signApk = version_info + '_' + eachChannelApk
            # copy apk
            configScr.copyFile(baseapk[0], preChannelApkDir)
            # add sourced
            configScr.addSourcedFile(preChannelApkDir, eachCode)
            # get sign info
            signInfo = getModelInfo.getSignInfo()
            # add sign
            configScr.signApk(configInfo.signPath, signInfo[1], signApkDir, preChannelApkDir, signInfo[0])
            # delete jiagu apk
            configScr.deleteReinforceApk(preChannelApkDir)
            # get pre version
            version = configScr.getVersionFromFile()
            # creat download url
            # preDlUrl = configInfo.preDownLoadUrl + eachChannelApk
            preDlUrl = configInfo.preDownLoadUrl + signApk
            print 'preDlurl:', preDlUrl
            # db --> download url
            getModelInfo.addUrl(version, eachName, eachCode, preDlUrl, '360', '')
            # db --> history download url
            getModelInfo.addHisUrl(version, eachName, eachCode, eachChannelApk, '360', '')
        # pigeonhole 归档
        # configScr.dirExit(configInfo.historyDownloadDir)
        # Create the corresponding version folder
        configScr.baseApkManage()
        configScr.channelApkMange()
        configScr.baseApkDelete()
        endTime = datetime.datetime.now()
        print 'endtime:', endTime
        print '360耗时:', (endTime - startTime).seconds
        print '结束360'

    pass


class myThread_build_bd(threading.Thread):
    def __init__(self, bd):
        self.bd = bd
        threading.Thread.__init__(self)

    def run(self):
        startTime = datetime.datetime.now()
        print 'startTime:', startTime
        print '开始百度构建'
        # get bd base apk
        baseApk = configScr.getBaseApkPath()  # baseapk type:array
        # get channelCode && channelName
        code = getModelInfo.new_bd_code()
        name = getModelInfo.new_bd_name()
        version_info = filetool.getVersionFromFile()
        for indexInfo in range(len(code)):
            # get each name && code
            eachCode = code[indexInfo]
            eachName = name[indexInfo]
            # creat channelApk name
            eachChannelApk = 'bd-' + eachName + '-' + eachCode + '.apk'
            configScr.dirExit(configInfo.presentChannelApkPath)
            preChannelApkDir = configInfo.presentChannelApkPath + eachChannelApk
            signApkDir = configInfo.signapkName + version_info + '_' + eachChannelApk
            signApk = version_info + '_' + eachChannelApk
            # copy apk
            configScr.copyFile(baseApk[0], preChannelApkDir)
            # add sourced
            configScr.addSourcedFile(preChannelApkDir, eachCode)
            # get sign info
            signInfo = getModelInfo.getSignInfo()
            # add sign
            configScr.signApk(configInfo.signPath, signInfo[1], signApkDir, preChannelApkDir, signInfo[0])
            # delete jiagu apk
            configScr.deleteReinforceApk(preChannelApkDir)
            # get pre version
            version = configScr.getVersionFromFile()
            # creat download url
            # preDlUrl = configInfo.preDownLoadUrl + eachChannelApk
            preDlUrl = configInfo.preDownLoadUrl + signApk
            print 'preDlurl:', preDlUrl
            # db --> download url
            getModelInfo.addUrl(version, eachName, eachCode, preDlUrl, 'bd', '')
            # db --> history download url
            getModelInfo.addHisUrl(version, eachName, eachCode, eachChannelApk, 'bd', '')
        configScr.baseApkManage()
        configScr.channelApkMange()
        configScr.baseApkDelete()
        endTime = datetime.datetime.now()
        print 'endtime:', endTime
        print '百度耗时:', (endTime - startTime).seconds
        print '结束百度构建'


def thred_360(request):
    # 开启子线程进行构建
    thread1 = myThread_build_360(360)
    thread1.start()
    return render(request, 'channnewnew/buildTip.html')


def thred_bd(request):
    # 开启子线程进行构建
    thread2 = myThread_build_bd('bd')
    thread2.start()
    return render(request, 'channnewnew/buildTip.html')


def build_360(request):
    # get 360 base apk
    baseapk = configScr.getBaseApkPath()  # baseapk type:array
    # get channelCode && channelName
    code = getModelInfo.new_360_code()
    name = getModelInfo.new_360_name()
    print 'code', code
    print 'name', name
    for indexInfo in range(len(code)):
        # get each name && code
        eachCode = code[indexInfo]
        eachName = name[indexInfo]
        eachChannelApk = '360-' + eachName + '-' + eachCode + '.apk'
        print eachChannelApk
        configScr.dirExit(configInfo.presentChannelApkPath)
        preChannelApkDir = configInfo.presentChannelApkPath + eachChannelApk
        signApkDir = configInfo.signapkName + eachChannelApk
        # copy apk
        configScr.copyFile(baseapk[0], preChannelApkDir)
        # add sourced
        configScr.addSourcedFile(preChannelApkDir, eachCode)
        # get sign info
        signInfo = getModelInfo.getSignInfo()
        # add sign
        print configInfo.signPath, signInfo[1], signApkDir, preChannelApkDir, signInfo[0]
        configScr.signApk(configInfo.signPath, signInfo[1], signApkDir, preChannelApkDir, signInfo[0])
        print 'sign--------'
        # delete jiagu apk
        configScr.deleteReinforceApk(preChannelApkDir)
        # get pre version
        version = configScr.getVersionFromFile()
        # creat download url
        preDlUrl = configInfo.preDownLoadUrl + eachChannelApk
        # db --> download url
        getModelInfo.addUrl(version, eachName, eachCode, preDlUrl, '360', '')
        # db --> history download url
        getModelInfo.addHisUrl(version, eachName, eachCode, eachChannelApk, '360', '')
    # pigeonhole 归档
    # configScr.dirExit(configInfo.historyDownloadDir)
    # Create the corresponding version folder
    configScr.baseApkManage()
    configScr.channelApkMange()
    configScr.baseApkDelete()
    print '归档完毕 ok'

    return HttpResponse('hao;e')


def build_bd(request):
    # get bd base apk
    baseApk = configScr.getBaseApkPath()  # baseapk type:array
    # get channelCode && channelName
    code = getModelInfo.new_bd_code()
    name = getModelInfo.new_bd_name()
    for indexInfo in range(len(code)):
        # get each name && code
        eachCode = code[indexInfo]
        eachName = name[indexInfo]
        # creat channelApk name
        eachChannelApk = 'bd-' + eachName + '-' + eachCode + '.apk'
        print eachChannelApk
        configScr.dirExit(configInfo.presentChannelApkPath)
        preChannelApkDir = configInfo.presentChannelApkPath + eachChannelApk
        signApkDir = configInfo.signapkName + eachChannelApk
        # copy apk
        configScr.copyFile(baseApk[0], preChannelApkDir)
        # add sourced
        configScr.addSourcedFile(preChannelApkDir, eachCode)
        # get sign info
        signInfo = getModelInfo.getSignInfo()
        # add sign
        print configInfo.signPath, signInfo[1], signApkDir, preChannelApkDir, signInfo[0]
        configScr.signApk(configInfo.signPath, signInfo[1], signApkDir, preChannelApkDir, signInfo[0])
        print 'sign--------'
        # delete jiagu apk
        configScr.deleteReinforceApk(preChannelApkDir)
        # get pre version
        version = configScr.getVersionFromFile()
        # creat download url
        preDlUrl = configInfo.preDownLoadUrl + eachChannelApk
        # db --> download url
        getModelInfo.addUrl(version, eachName, eachCode, preDlUrl, 'bd', '')
        # db --> history download url
        getModelInfo.addHisUrl(version, eachName, eachCode, eachChannelApk, 'bd', '')
    configScr.baseApkManage()
    configScr.channelApkMange()
    configScr.baseApkDelete()

    return HttpResponse('ok ;l')


def linshiChannelApk(request):
    '''
    linshi jdb渠道包-bd
    '''
    bd_channelinfo = ChannelListConfig.objects.filter(jiagu='bd', projectshortname='jdb')
    bd_channelName = []
    bd_channelCode = []
    for channelInfo in bd_channelinfo:
        bd_channelName.append(channelInfo.name)
        bd_channelCode.append(channelInfo.code)

    print bd_channelName
    print bd_channelCode
    for indexx in range(len(bd_channelName)):
        eachChannelName = bd_channelName[indexx]
        eachChannelcode = bd_channelCode[indexx]
        # new channel apk
        NewApkName = 'jdb_3060.db_' + eachChannelName + '-' + eachChannelcode + '.apk'
        # cunchu
        channelApk = 'channel/staticc/JdbChannel/3060_bd/' + NewApkName

        # get base apk
        baseApkName = filetool.getBaseApkPath()
        # copy -->get channelApk
        Util.copyFile(baseApkName[0], channelApk)

        # add channel info -->channelapk
        channelBuildApk.getAChannelApk(NewApkName, eachChannelcode)

        # add download url -->db

    return JsonResponse('ssss')


def getChannel_360(request):
    '''
    临时渠道包-360
    '''
    channelinfo_360 = Channellist.objects.filter(jiagu='360')

    channelName_360 = []
    channelCode_360 = []
    for channelInfoo in channelinfo_360:
        channelName_360.append(channelInfoo.name)
        channelCode_360.append(channelInfoo.code)
    print channelName_360
    print channelCode_360

    for indexx in range(len(channelName_360)):
        eachChannelName = channelName_360[indexx]
        eachChannelcode = channelCode_360[indexx]
        # new channel apk
        NewApkName = 'jdb_3060.360_' + eachChannelName + '-' + eachChannelcode + '.apk'
        # cunchu
        channelApk = 'channel/staticc/JdbChannel/3060_360/' + NewApkName

        # get base apk
        baseApkName = filetool.getBaseApkPath()
        # copy -->get channelApk
        Util.copyFile(baseApkName[0], channelApk)

        # add channel info -->channelapk
        channelBuildApk.getAChannelApk(NewApkName, eachChannelcode)

    return JsonResponse('zzzz')


def uploadify_script(request):
    """
    通过bootstrap fileinput 上传图片
    """
    result = {"data": []}
    path = os.path.join(dev.UPLOADFILES)

    try:
        response = HttpResponse()
        response['Content-Type'] = "text/javascript"
        ret = -1
        file = request.FILES.get("file_data", None)
        if file:
            imgurl = filetool._upload(file, path)
            if not imgurl:
                ret = 1
            ret = 0
            result["imgurl"] = imgurl
            # result.update(code_msg(ret))
        return JsonResponse(result)

    except Exception:
        return JsonResponse(result)


def downloadApkInfo(request):
    '''
    db交互，将渠道包渠道号及下载链接返回至前端页面
    '''
    # 默认返回当前版本的渠道包
    version = configScr.getVersionFromFile()

    # allApkInfo = Androidnodestatus.objects.filter(status=version)
    # strip()去除空格，防止多余空格影响操作
    allApkInfo = PreChannelDownload.objects.filter(version=version.strip())
    print 'allApkInfo:', allApkInfo
    return render(request, 'channnewnew/cheakChannelApk.html', {'apkInfo': allApkInfo, 'version': version})


def apkMange(request):
    '''
    :return: 包归档管理，负责母包及渠道包的历史版本的存档管理
    '''
    apkVersion = '3050'
    apkName = filetool.getBaseApkName()
    channelNum = getModelInfo.get_360_info_channelNum()
    chanelName = getModelInfo.get_360_info_channelName()
    # 获取渠道包name 传给端
    channelApkDowList = []

    for eachChannelApk in range(len(channelNum)):
        eachChannelName = chanelName[eachChannelApk]
        eachChannelNum = channelNum[eachChannelApk]
        channelApkName = eachChannelName + '-' + eachChannelNum + '.apk'
        channelApkDowList.append(channelApkName)
    return render(request, 'channnewnew/apkManage.html',
                  {'apkVersion': apkVersion, 'apkName': apkName[0], 'apkList': channelApkDowList,
                   'channelname': chanelName})

    # return HttpResponse('待开发')


def useExplain(request):
    # 使用说明
    return render(request, 'channnewnew/explain.html')


def viewChannelNum(request):
    channel_list = ChannelListConfig.objects.all().filter(isdel=0).values()
    ret = {}
    title, ch_list = [], []
    if len(channel_list) != 0:
        for item in channel_list:
            if item['name']:
                title.append(item['name'])
                print str(item['update_time']).split('.')[0]

                item['update_time'] = str(item['update_time']).split('.')[0]
                ch_list.append(item)

    ret['title'] = title
    ret['list'] = ch_list
    print ret['list']
    return render(request, 'channnewnew/viewChannelNum.html', {"list": ret['list']})


@csrf_exempt
def delChannelCode(request):
    data = request.POST
    id = data.get('id')
    print id
    content = ChannelListConfig.objects.get(id=id)
    print content
    if content:
        content.isdel = 1
        content.save()
    response_data = {"code": 200, "msg": "删除成功"}
    return JsonResponse(response_data)


def buildResult(request):
    return render(request, 'channnewnew/buildResult.html')


@csrf_exempt
def retChannelCodel(request):
    # test case
    data = request.POST
    print data
    a = data.get('a')
    b = data.get('b')
    response_data = {}
    response_data['result'] = 'only test'
    response_data['message'] = a
    return JsonResponse(response_data)


@csrf_exempt
def getHistoryVersion(request): \
        # ajax 请求，获取对应版本的渠道包下载链接
    data = request.POST
    # 获取端上传版本号
    version = data.get('version')
    responseData = {}
    downloadurl = []
    # db查询渠道包
    # historyChennelApk = HistoryChannelapk.objects.filter(version=version).values('downloadrl')
    historyChennelApk = HisChannelDownload.objects.filter(version=version).values('downloadurl')
    if len(list(historyChennelApk)) != 0:
        historyChennelApkk = list(historyChennelApk)
        responseData['dd'] = historyChennelApkk
        return JsonResponse(responseData)
    else:
        responseData['errorinfo'] = 'no version'
        return JsonResponse(responseData)


def testXml(request):
    # 测试返回xml格式数据
    return render_to_response('channnewnew/aa.xml', content_type='application/xml')
